package cn.itcast.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.itcast.pojo.BaseDict;
import cn.itcast.pojo.Customer;
import cn.itcast.pojo.QueryVo;
import cn.itcast.service.CustomerService;
import cn.itcast.utils.Page;


@Controller
@RequestMapping("/customer")
public class CustomerAction {
	
	@Resource
	CustomerService customerService;
		
	@RequestMapping("/list")
	public String list(Model model,QueryVo queryVo)throws UnsupportedEncodingException {
		//处理get请求的乱码
		if(queryVo.getCustName() != null && !queryVo.getCustName().trim().equals("")){
			queryVo.setCustName(new String(queryVo.getCustName().getBytes("ISO8859-1"),"UTF-8"));
		}
		
		System.out.println("失路英雄");
		//客户来源条件补充
		List<BaseDict> customerSourceList = customerService.findDictByTypeCode("002");
		model.addAttribute("fromType",customerSourceList);
		
		//客户所属行业条件填充
		List<BaseDict> customerIndustryList = customerService.findDictByTypeCode("001");
		model.addAttribute("industryType", customerIndustryList);
		
		//客户所属行业条件填充
		List<BaseDict> customerLeveList = customerService.findDictByTypeCode("006");
		model.addAttribute("levelType", customerLeveList);
		
		//参数数据回显
		model.addAttribute("vo", queryVo);
		
		List<Customer> customerList = customerService.findCustomerList(queryVo);
		
		//查下客户的总记录数
		Integer customerCount = customerService.findCustomerCount(queryVo);
		
		//初始化分页对象
		Page<Customer> pageObj = new Page<>();
		pageObj.setPage(queryVo.getPage());//要查询的页
		pageObj.setRows(customerList);//前台回显的客户数据
		pageObj.setSize(queryVo.getRows());//一页显示的条数
		pageObj.setTotal(customerCount);//符合条件的总客户条数
		model.addAttribute("page",pageObj);
		
		return "customer";	
	}
	
	@RequestMapping("/delete")
	public void delete(Integer id,HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		Integer deleteCount = customerService.deleteCustomerById(id);
		if(deleteCount == 1){
			response.getWriter().print("删除成功");
		}else{
			response.getWriter().print("删除失败");
		}
	}
	
	@RequestMapping("/edit")
	public void update(Customer customer,HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		Integer updateCount = customerService.updateCustomer(customer);
		if(updateCount == 1){
			response.getWriter().print("更新客户成功");
		}else{
			response.getWriter().print("更新客户失败");
		}
	}

}
